//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.BusinessLogic.Utils;

namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class ProductBox1Control : BaseNopFrontendUserControl
    {
        private IProductService _productService;
        private IPictureService _pictureService;
        private IShoppingCartService _shoppingCartService;
        private ISettingService _settingService;
        private int _productImageSize = 125;
        private Product _product = null;
        private IList<Bundle> _bundles;

        public ProductBox1Control()
        {
            _productService = IoC.Resolve<IProductService>();
            _pictureService = IoC.Resolve<IPictureService>();
            _shoppingCartService = IoC.Resolve<IShoppingCartService>();
            _settingService = IoC.Resolve<ISettingService>();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Load += new EventHandler(ProductBox1Control_Load);
            rptProductBundles.ItemDataBound += new RepeaterItemEventHandler(rptProductBundles_ItemDataBound);
            btnAddToCart.Command += new CommandEventHandler(btnAddToCart_Click);
        }

        void ProductBox1Control_Load(object sender, EventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            if (_product != null) {
                string productURL = SEOHelper.GetProductUrl(_product);

                lnkProductDetails.NavigateUrl = hlProduct.NavigateUrl = productURL;
                hlProduct.Text = Server.HtmlEncode(_product.LocalizedName);

                var picture = _product.DefaultPicture;
                if (picture != null) {
                    hlImageLink.ImageUrl = _pictureService.GetPictureUrl(picture, this.ProductImageSize, true);
                    hlImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), _product.LocalizedName);
                    hlImageLink.Text = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), _product.LocalizedName);
                } else {
                    hlImageLink.ImageUrl = _pictureService.GetDefaultPictureUrl(this.ProductImageSize);
                    hlImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), _product.LocalizedName);
                    hlImageLink.Text = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), _product.LocalizedName);
                }

                hlImageLink.NavigateUrl = productURL;
                lShortDescription.Text = _product.LocalizedShortDescription;

                var productBundles = _product.ProductBundles;
                if (productBundles != null && productBundles.Count > 0) {
                    pnlProductBundles.Visible = true;
                    rptProductBundles.DataSource = productBundles;
                    rptProductBundles.DataBind();
                } else {
                    pnlProductBundles.Visible = false;
                }

                var productVariantCollection = _product.ProductVariants;
                if (productVariantCollection.Count > 0) {
                    if (!_product.HasMultipleVariants) {
                        var productVariant = productVariantCollection[0];
                        btnAddToCart.Visible = (!productVariant.DisableBuyButton);
                        if (!_settingService.GetSettingValueBoolean("Common.HidePricesForNonRegistered") ||
                            (NopContext.Current.User != null &&
                            !NopContext.Current.User.IsGuest)) {
                            //nothing
                        } else {
                            btnAddToCart.Visible = false;
                        }
                    } else {
                        btnAddToCart.Visible = false;
                    }
                } else {
                    btnAddToCart.Visible = false;
                }

                if (_settingService.GetSettingValueBoolean("Product.Bundle.ShowSave")) {
                    // get total bundle variants price
                    decimal bundlePrice = 0;
                    Bundles.ToList().ForEach(b => {
                        bundlePrice += b.ProductVariant.Price;
                    });
                    decimal bundleSave = bundlePrice - ProductVariant.Price;

                    litBundleSave.Visible = true;
                    litBundleSave.Text = string.Format(GetLocaleResourceString("Product.Bundle.Save"), PriceHelper.FormatPrice(bundleSave));
                } else {
                    litBundleSave.Visible = false;
                }
            }
        }

        protected void btnAddToCart_Click(object sender, CommandEventArgs e)
        {
            int productId = Convert.ToInt32(e.CommandArgument);
            int productVariantId = 0;
            if (_productService.DirectAddToCartAllowed(productId, out productVariantId)) {
                var addToCartWarnings = _shoppingCartService.AddToCart(ShoppingCartTypeEnum.ShoppingCart, productVariantId, string.Empty, decimal.Zero, 1);
                if (addToCartWarnings.Count == 0) {
                    bool displayCart = true;
                    if (this.RedirectCartAfterAddingProduct.HasValue)
                        displayCart = this.RedirectCartAfterAddingProduct.Value;
                    else
                        displayCart = _settingService.GetSettingValueBoolean("Display.Products.DisplayCartAfterAddingProduct");

                    if (displayCart) {
                        //redirect to shopping cart page
                        Response.Redirect(SEOHelper.GetShoppingCartUrl());
                    } else {
                        //display notification message
                        this.DisplayAlertMessage(GetLocaleResourceString("Products.ProductHasBeenAddedToTheCart"));
                    }
                } else {
                    string productURL = SEOHelper.GetProductUrl(productId);
                    Response.Redirect(productURL);
                }
            } else {
                string productURL = SEOHelper.GetProductUrl(productId);
                Response.Redirect(productURL);
            }
        }

        void rptProductBundles_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
                var bundle = e.Item.DataItem as Bundle;
                if (bundle != null) {
                    var hlProductName = e.Item.FindControl("hlProductName") as HyperLink;
                    hlProductName.Text = bundle.ProductVariant.Product.LocalizedName;
                    hlProductName.NavigateUrl = SEOHelper.GetProductUrl(bundle.ProductVariant.Product);

                    var hlProductImage = e.Item.FindControl("hlProductImage") as HyperLink;
                    hlProductImage.ImageUrl = _pictureService.GetPictureUrl(bundle.ProductVariant.Product.DefaultPicture.PictureId, _settingService.GetSettingValueInteger("Media.Category.ThumbnailImageSize", 125), true);
                    hlProductImage.Width = Unit.Pixel(125);
                    hlProductImage.Height = Unit.Pixel(125);
                    hlProductImage.NavigateUrl = hlProductName.NavigateUrl;
                    hlProductImage.ToolTip = String.Format(GetLocaleResourceString("Media.Category.ImageLinkTitleFormat"), bundle.ProductVariant.Product.LocalizedName);
                    hlProductImage.Text = String.Format(GetLocaleResourceString("Media.Category.ImageAlternateTextFormat"), bundle.ProductVariant.Product.LocalizedName);
                }
            }
        }

        public Product Product
        {
            get
            {
                return _product;
            }
            set
            {
                _product = value;
            }
        }

        public ProductVariant ProductVariant
        {
            get
            {
                if (Product != null && Product.ProductVariants.Count > 0) {
                    return Product.ProductVariants[0];
                }
                return null;
            }
        }

        public IList<Bundle> Bundles
        {
            get
            {
                if (_bundles == null) {
                    _bundles = _productService.GetAllBundlesByProductId(Product.ProductId);
                }

                return _bundles;
            }
        }

        public int ProductImageSize
        {
            get
            {
                return _settingService.GetSettingValueInteger("Media.Product.ThumbnailImageSize", _productImageSize);
            }
            set
            {
                _productImageSize = value;
            }
        }

        /// <summary>
        /// Gets or sets a value whether we redirects a customer to shopping cart page after adding a product to the cart (overrides "Display.Products.DisplayCartAfterAddingProduct" settings)
        /// </summary>
        public bool? RedirectCartAfterAddingProduct
        {
            get
            {
                if (ViewState["RedirectCartAfterAddingProduct"] == null)
                    return null;
                else
                    return (bool)ViewState["RedirectCartAfterAddingProduct"];
            }
            set
            {
                ViewState["RedirectCartAfterAddingProduct"] = value;
            }
        }
    }
}